<!-- 已弃用 -->
<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    @ok="onButtonOkClick"
    width="600px"
  >
    <BasicTable
      @register="registerTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
    >
      <!-- 部门名称按层级设置缩进 -->
      <template #name="{ record }">
        <template v-if="record.level === 0">
          <span>{{ record.name }}</span>
        </template>
        <template v-if="record.level === 1">
          <span style="display: block; text-indent: 1em">{{ record.name }}</span>
        </template>
        <template v-if="record.level === 2">
          <span style="display: block; text-indent: 2em">{{ record.name }}</span>
        </template>
      </template>
    </BasicTable>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref, inject } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { deptTableColumns } from './category.data';
  import { getDepts, setDepts } from '/@/api/cms/category';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { BasicTable, useTable } from '/@/components/Table';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'SetDeptRelation',
    components: { BasicModal, BasicTable },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是关联部门设置
      const op = ref(OperationTypeEnum.UN_KNOWN);

      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');
      const moduleName = inject<string>('moduleName');

      //栏目id集合
      const cids = ref<number[] | string[]>([]);
      //部门id集合
      const dids = ref<number[] | string[]>([]);

      //返回的部门数据
      const deptsData = reactive({
        checkedKeys: [],
        depts: [],
      });

      const [registerTable, { getSelectRowKeys, setSelectedRowKeys, clearSelectedRowKeys }] =
        useTable({
          title: '部门列表',
          dataSource: deptsData.depts,
          columns: deptTableColumns, //表头数据
          showTableSetting: true, //是否显示表格设置
          bordered: true,
          showIndexColumn: false,
          pagination: false, //关闭分页
          rowSelection: { type: 'checkbox' },
          rowKey: 'id',
          clickToRowSelect: true,
        });

      /**
       * 根据父组件传递过来的参数获取对应的数据
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //每次打开不同栏目窗口都会添加一次栏目id,接收前如果有则清空
        if (cids.value.length > 0) {
          cids.value = [];
        }

        //接收父组件传递的数据
        console.log(data);
        //判断是否传入op属性
        if (data?.op) {
          op.value = data.op;
        }

        if (data?.dataId) {
          cids.value.push(data.dataId);
        }
        if (data?.cids) {
          cids.value = data.cids;
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        setModalProps({ confirmLoading: false });

        get();

        //后台返回的数据如果有已经关联的部门则设置选中行
        setSelectedRowKeys(deptsData.checkedKeys);
      });

      //获取部门信息
      async function get() {
        //每次打开窗口都会重复加载数据，在加载数据前如果有数据先清空
        if (deptsData.depts.length > 0) {
          deptsData.depts = [];
          deptsData.checkedKeys = [];
        }
        //调用后端接口获取数据
        getDepts(cids.value)
          .then((res) => {
            console.log('res', res);
            //处理返回数据
            res.forEach((val) => {
              deptsData.depts.push(val.dept);
              //获取设置部门之前已经关联的部门id，用于回显勾选
              if (val.checked === true) {
                deptsData.checkedKeys.push(val.dept.id);
              }
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，调用接口保存关联信息
       */
      async function onButtonOkClick() {
        //获取设置选中的部门id集合
        dids.value = getSelectRowKeys();

        try {
          setModalProps({ confirmLoading: true });
          //调用接口进行保存
          setDepts({ cids: cids.value, dids: dids.value })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('设置成功', 2);
              }
              closeModal();
              emit('success');
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } finally {
          setModalProps({ confirmLoading: false });
        }

        //清空选中的行
        clearSelectedRowKeys();
      }

      return {
        op,
        moduleName,
        modalTitle,
        registerModal,
        registerTable,
        onButtonOkClick,
        get,
      };
    },
  });
</script>
